package com.joyd.lib.screen

import android.os.Handler
import android.os.Looper
import android.view.MotionEvent
import android.view.View

/**
 * Screen工具类，提供屏幕相关操作
 */
object ScreenUtils {
    
    /**
     * 点击指定的View
     * @param view 要点击的View对象
     */
    fun click(view: View) {
        // 确保在UI线程执行点击操作
        if (Looper.myLooper() == Looper.getMainLooper()) {
            performClick(view)
        } else {
            Handler(Looper.getMainLooper()).post {
                performClick(view)
            }
        }
    }
    
    /**
     * 执行View的点击操作
     * @param view 要点击的View对象
     */
    private fun performClick(view: View) {
        // 检查View是否可见且可点击
        if (view.isShown && view.isClickable) {
            // 使用MotionEvent模拟点击
            val x = view.width / 2f
            val y = view.height / 2f
            
            // 发送DOWN事件
            val downEvent = MotionEvent.obtain(
                System.currentTimeMillis(),
                System.currentTimeMillis(),
                MotionEvent.ACTION_DOWN,
                x,
                y,
                0
            )
            view.dispatchTouchEvent(downEvent)
            downEvent.recycle()
            
            // 发送UP事件
            val upEvent = MotionEvent.obtain(
                System.currentTimeMillis(),
                System.currentTimeMillis(),
                MotionEvent.ACTION_UP,
                x,
                y,
                0
            )
            view.dispatchTouchEvent(upEvent)
            upEvent.recycle()
        }
    }
}